package com.msh.platform.elm.controller;

import com.msh.platform.bizmedia.base.conf.ResponseResult;
import com.msh.platform.bizmedia.base.util.SessionUtil;
import com.msh.platform.bizmedia.base.vo.SessionData;
import com.msh.platform.elm.common.constants.Constants;
import com.msh.platform.elm.entity.ShopCartItem;
import com.msh.platform.elm.entity.WxPubNo;
import com.msh.platform.elm.service.BuyerOrderService;
import com.msh.platform.elm.service.SaleInfoService;
import com.msh.platform.elm.service.ShopCartItemService;
import com.msh.platform.elm.service.WxPubNoService;
import com.msh.platform.elm.vo.PageXcxVO;
import com.msh.platform.elm.vo.QuerySaleInfoVO;
import com.msh.platform.elm.vo.SaleInfoVO;
import com.msh.platform.elm.vo.SaveOrderVO;
import com.msh.platform.elm.vo.SignVO;
import com.msh.platform.elm.common.util.SortUtils;
import com.msh.platform.elm.common.util.MapTrunPojoUtils;

import org.springframework.data.domain.Sort;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.text.ParseException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.validation.Valid;

/**
 * @Author zhangyangsong
 * @Description :
 * @Date: Created in 2018/11/8
 * @Copyright: ©2018 all rights reserved.
 */
@RestController
@RequestMapping(value = "/buyer")
@Api(tags = "小程序端接口")
@Slf4j
public class BuyerController extends BaseController{

    @Autowired
    private WxPubNoService wxPubNoService;
    @Autowired
    private SaleInfoService saleInfoService;
    @Autowired
    private ShopCartItemService shopCartItemService;
    @Autowired
    private BuyerOrderService buyerOrderService;
    
    @ApiOperation(value = "获取公众号列表")
    @PostMapping(path = "/get_pub_no_page")
    public ResponseResult<Page<WxPubNo>> get_pub_no_page(@RequestBody @Valid PageXcxVO paramVo, BindingResult errors) {
    	if (errors.hasErrors()){  //参数校验失败
			//返回参数校验错误信息
    		return ResponseResult.fail(Constants.RESP_FAIL, errors.getAllErrors().get(0).getDefaultMessage());
	    }
    	//校验sign字符串
    	Map<String, Object> signMap = MapTrunPojoUtils.object2Map(paramVo);
		String paramStr = SortUtils.sortMap(signMap);
		boolean flag = validateSign(paramStr, paramVo.getSign());
		log.info("验证签名结果：" + flag);
		if(flag){
			SessionData sessionData = SessionUtil.getLocalUserInfo();
			if(sessionData!=null) {
				Sort sort = new Sort(Sort.Direction.DESC,"createTime"); //创建时间降序排序
				Pageable pageable = PageRequest.of(paramVo.getPageNo(), paramVo.getPageSize(), sort);
				Page<WxPubNo> wxPubNoList = wxPubNoService.findAll(pageable);
				return ResponseResult.success(wxPubNoList);
			}else {
				return ResponseResult.fail(Constants.RESP_TOKEN_TIMEOUT, "未登录或登录超时");
			}
		}else {
			return ResponseResult.fail(Constants.RESP_FAIL, "签名校验失败");
		}
    		
    }
    
    @ApiOperation(value = "获取公众号详情")
    @PostMapping(path = "/get_pub_no_detail/{id}")
    public ResponseResult<WxPubNo> get_pub_no_detail(@PathVariable int id,@RequestBody @Valid SignVO paramVo,BindingResult errors) {
    	if (errors.hasErrors()){  //参数校验失败
			//返回参数校验错误信息
    		return ResponseResult.fail(Constants.RESP_FAIL, errors.getAllErrors().get(0).getDefaultMessage());
	    }
    	//校验sign字符串
    	Map<String, Object> signMap = new HashMap<String, Object>();
		signMap.put("id", id);
		String paramStr = SortUtils.sortMap(signMap);
		boolean flag = validateSign(paramStr, paramVo.getSign());
		log.info("验证签名结果：" + flag);
		if(flag){
			SessionData sessionData = SessionUtil.getLocalUserInfo();
			if(sessionData!=null) {
				WxPubNo wxPubNo = wxPubNoService.getWxPubNo(id);
				return ResponseResult.success(wxPubNo);
			}else {
				return ResponseResult.fail(Constants.RESP_TOKEN_TIMEOUT, "未登录或登录超时");
			}
		}else {
			return ResponseResult.fail(Constants.RESP_FAIL, "签名校验失败");
		}
    		
    }
    
    @ApiOperation(value = "获取公众号档期的出售版位列表")
    @PostMapping(path = "/get_dq_position")
    public ResponseResult<List<SaleInfoVO>> getDqPosition(@RequestBody @Valid QuerySaleInfoVO paramVo, BindingResult errors) throws ParseException {
    	if (errors.hasErrors()){  //参数校验失败
			//返回参数校验错误信息
    		return ResponseResult.fail(Constants.RESP_FAIL, errors.getAllErrors().get(0).getDefaultMessage());
	    }
    	//校验sign字符串
    	Map<String, Object> signMap = MapTrunPojoUtils.object2Map(paramVo);
		String paramStr = SortUtils.sortMap(signMap);
		boolean flag = validateSign(paramStr, paramVo.getSign());
		log.info("验证签名结果：" + flag);
		if(flag){
			SessionData sessionData = SessionUtil.getLocalUserInfo();
			if(sessionData!=null) {
				String dqStr = paramVo.getDqStr();
				List<SaleInfoVO> saleList = saleInfoService.getDqSale(paramVo.getId(), dqStr);
				return ResponseResult.success(saleList);
			}else {
				return ResponseResult.fail(Constants.RESP_TOKEN_TIMEOUT, "未登录或登录超时");
			}
		}else {
			return ResponseResult.fail(Constants.RESP_FAIL, "签名校验失败");
		}	
    }
    
    @ApiOperation(value = "加入投放车")
    @PostMapping(path = "/put_shop_car/{id}")
    @ApiImplicitParam(name="id",value="公众号id",required=true,paramType="path",dataType="int")
    public ResponseResult putShopCar(@PathVariable int id,@RequestBody @Valid SignVO paramVo,BindingResult errors) throws ParseException {
    	if (errors.hasErrors()){  //参数校验失败
			//返回参数校验错误信息
    		return ResponseResult.fail(Constants.RESP_FAIL, errors.getAllErrors().get(0).getDefaultMessage());
	    }
    	//校验sign字符串
    	Map<String, Object> signMap = new HashMap<String, Object>();
		signMap.put("id", id);
		String paramStr = SortUtils.sortMap(signMap);
		boolean flag = validateSign(paramStr, paramVo.getSign());
		log.info("验证签名结果：" + flag);
		if(flag){
			SessionData sessionData = SessionUtil.getLocalUserInfo();
			if(sessionData!=null) {
				shopCartItemService.addShopCartItem(sessionData.getId(), id);
				return ResponseResult.success(null);
			}else {
				return ResponseResult.fail(Constants.RESP_TOKEN_TIMEOUT, "未登录或登录超时");
			}
		}else {
			return ResponseResult.fail(Constants.RESP_FAIL, "签名校验失败");
		}	
    }
    
    @ApiOperation(value = "删除投放车中的商品")
    @PostMapping(path = "/del_shop_car_item/{id}")
    @ApiImplicitParam(name="id",value="投放车中的商品id",required=true,paramType="path",dataType="int")
    public ResponseResult delShopCarItem(@PathVariable String id,@RequestBody @Valid SignVO paramVo,BindingResult errors) throws ParseException {
    	if (errors.hasErrors()){  //参数校验失败
			//返回参数校验错误信息
    		return ResponseResult.fail(Constants.RESP_FAIL, errors.getAllErrors().get(0).getDefaultMessage());
	    }
    	//校验sign字符串
    	Map<String, Object> signMap = new HashMap<String, Object>();
		signMap.put("id", id);
		String paramStr = SortUtils.sortMap(signMap);
		boolean flag = validateSign(paramStr, paramVo.getSign());
		log.info("验证签名结果：" + flag);
		if(flag){
			SessionData sessionData = SessionUtil.getLocalUserInfo();
			if(sessionData!=null) {
				shopCartItemService.delShopCartItem(id);
				return ResponseResult.success(null);
			}else {
				return ResponseResult.fail(Constants.RESP_TOKEN_TIMEOUT, "未登录或登录超时");
			}
		}else {
			return ResponseResult.fail(Constants.RESP_FAIL, "签名校验失败");
		}	
    }
    
    @ApiOperation(value = "获取投放车中的公众号记录")
    @PostMapping(path = "/get_shop_car_item")
    @ApiImplicitParam(name="id",value="投放车中的商品id",required=true,paramType="path",dataType="int")
    public ResponseResult getShopCarItem() throws ParseException {
		SessionData sessionData = SessionUtil.getLocalUserInfo();
		if(sessionData!=null) {
			List<ShopCartItem> itemList = shopCartItemService.queryCartItem(sessionData.getId());
			return ResponseResult.success(itemList);
		}else {
			return ResponseResult.fail(Constants.RESP_TOKEN_TIMEOUT, "未登录或登录超时");
		}
    }
    
    @ApiOperation(value = "下单")
    @PostMapping(path = "/save_order")
    public ResponseResult saveOrder(@RequestBody @Valid SaveOrderVO paramVo, BindingResult errors) throws ParseException {
    	if (errors.hasErrors()){  //参数校验失败
			//返回参数校验错误信息
    		return ResponseResult.fail(Constants.RESP_FAIL, errors.getAllErrors().get(0).getDefaultMessage());
	    }
    	//校验sign字符串
    	Map<String, Object> signMap = MapTrunPojoUtils.object2Map(paramVo);
		String paramStr = SortUtils.sortMap(signMap);
		boolean flag = validateSign(paramStr, paramVo.getSign());
		log.info("验证签名结果：" + flag);
		if(flag){
			SessionData sessionData = SessionUtil.getLocalUserInfo();
			if(sessionData!=null) {
				buyerOrderService.saveOrder(sessionData.getId(), paramVo);
				return ResponseResult.success(null);
			}else {
				return ResponseResult.fail(Constants.RESP_TOKEN_TIMEOUT, "未登录或登录超时");
			}
		}else {
			return ResponseResult.fail(Constants.RESP_FAIL, "签名校验失败");
		}	
    }
    
}
